require 'rubygems'
require 'blather'
require 'pp'

include Blather

module Epic
	class Client


    # Create a new ad-hoc commands DSL
    #
    # @param [Blather::Client] client the client who's connection will be used
		def initialize(client)
			@client = client
		end

    # Retrieve Commands
    #
		def commands(peer,&callback)
			items = Stanza::Disco::DiscoItems.new :get, Stanza::Iq::Command.registered_ns
			items.to = peer
			request items, :items, callback
		end

    # Retrieve Info on single (command) node
    #
		def info(peer,cmd_node,&callback)
			query = Stanza::Disco::DiscoInfo.new :get, cmd_node
			query.to = peer
			request query, :query, callback
		end

    # Execute specific command on node
    #
		def execute(peer,cmd_node,&callback)
			cmd = Stanza::Iq::Command.new
			cmd.to = peer
			cmd.node = cmd_node
			request cmd, nil, callback
		end

    # Execute specific command on node, fillout form and resubmit
    #
		## no spec yet
		def submit(peer,cmd_node,hash,&callback)
			cmd = Stanza::Iq::Command.new
			cmd.to = peer
			cmd.node = cmd_node
			my_proc = Proc.new do |res|
				res.submit! hash
				request res, nil, callback
			end
			request cmd, nil, my_proc
		#	request cmd, nil, Proc.new do |res| 
		#		res.submit! hash
		#		request res, nil, callback
		#	end
		end

  private
    def request(node, method = nil, callback = nil, &block)
			## fixme - similar issue with pubsub dsl, not caught by test case
			##  - write testcase to detect, patch 
			callback = Proc.new {|m| puts m } if callback == nil 
      unless block_given?
        block = lambda do |node|
          callback.call(method ? node.__send__(method) : node)
        end
      end
      client.write_with_handler(node, &block)
    end

    def send_to(host = nil)
      raise 'You must provide a host' unless (host ||= @host)
      host
    end

    def client
      @client
    end
  end 
end

## add to dsl
module Blather::DSL
	def epic
		@epic ||= Epic::Client.new client
	end
end
